import * as widgets from "./index";
import ReactDOM from "react-dom";
import React from "react";
import { createRenderWidget } from "./context";
import less from "./client.less";

const renderWidgetsClient = () => {
  const clientPromises = [];
  Object.keys(widgets).forEach((key) => { });

  const widgetArray = Object.values(widgets);
  for (let widget of widgetArray) {
    const {
      widgetId,
      renderMode,
      Component,
      getInitState,
      reducer,
      action,
    } = widget;
    const container = document.getElementById(`${widgetId}--widget`);
    if (!container) {
      continue;
    }

    if (renderMode === "client") {
      const reqInfoStr = container.getAttribute("reqInfo");
      if (!reqInfoStr) {
        continue;
      }
      const { params, query } = JSON.parse(reqInfoStr);
      const p = Promise.resolve(getInitState(params, query)).then((state) => {
        const Widget = createRenderWidget(Component, state, reducer, action);
        ReactDOM.render(<Widget />, container);
      });
      clientPromises.push(p);
    } else if (renderMode === "server") {
      let state = {};
      let stateStr = container.getAttribute("state");
      if (stateStr) {
        state = JSON.parse(stateStr);
      }
      const Widget = createRenderWidget(Component, state, reducer, action);
      ReactDOM.hydrate(<Widget />, container);
    }
  }

  Promise.all(clientPromises).then((res) => {
    console.log("done");
  });
};

renderWidgetsClient();
console.log("after render call");
